import { RoleService } from "./role.service";
import { Body, Controller, Get, Post, Query } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { PaginationPipe } from "src/common/pipes/pagination.pipe";
import { ReqAddRoleDto, ReqSearchRoleDto, ReqUpdateRoleDto } from "./dto/req-role.dto";
import { DataObj } from "src/common/class/data-obj.class";
import { ApiException } from "src/common/exceptions/api.exception";

@ApiTags("角色管理")
@Controller("system/role")
export class RoleController {
  constructor(private readonly roleService: RoleService) {}

  // 分页查询
  @Get("getRoleList")
  async getRoleList(@Query(PaginationPipe) reqSearchRoleDto: ReqSearchRoleDto) {
    const res = await this.roleService.getRoleList(reqSearchRoleDto);
    return DataObj.create(res);
  }

  // 新增角色
  @Post("addRole")
  async addRole(@Body() reqAddRoleDto: ReqAddRoleDto) {
    const roleRes = await this.roleService.getRoleByNameOrKey(
      reqAddRoleDto.role_name,
      reqAddRoleDto.role_key,
    );
    if (roleRes && roleRes.length) throw new ApiException("该角色或权限已存在！");
    await this.roleService.addOrUpdateRole(reqAddRoleDto);
  }

  // 编辑角色
  @Post("editRole")
  async updateRole(@Body() reqUpdateRoleDto: ReqUpdateRoleDto) {
    const roleRes = await this.roleService.getRoleByNameOrKey(
      reqUpdateRoleDto.role_name,
      reqUpdateRoleDto.role_key,
    );
    let sameNameOrKey = 0;
    if (roleRes && roleRes.length) {
      roleRes.forEach((item) => {
        if (item.role_id != reqUpdateRoleDto.role_id) {
          sameNameOrKey += 1;
          return;
        }
      });
    }
    if (sameNameOrKey > 0) throw new ApiException("该角色或权限已存在！");
    await this.roleService.addOrUpdateRole(reqUpdateRoleDto);
  }

  // 删除角色
  @Post("deleteRole")
  async deleteRole(@Body("role_id") role_id: string) {
    await this.roleService.deleteRoleById(role_id);
  }
}
